package com.pig4cloud.pig.ads.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.api.entity.ResponseBean;
import com.pig4cloud.pig.api.entity.ThirdLandingPage;
import com.pig4cloud.pig.api.vo.ThirdLandingPageVo;
import com.pig4cloud.pig.ads.pig.mapper.TlpMapper;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.service.TlpService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @ 第三方落地页 前端控制器
 * @author yk
 */
@Log4j2
@RestController
@RequiredArgsConstructor
@RequestMapping("/thirdLandingPage")
@Api(value = "ThirdLandingPage", tags = "第三方落地页管理模块")
public class TlpController {

	@Autowired
	private final TlpService tlpService;

	@Autowired
	private final TlpMapper tlpMapper;

	@Autowired
	private final TtAccesstokenService ttAccesstokenService;

	private final AdvService advService;

	/**
	 * 分页查询落地页信息
	 * @return 分页对象
	 */
	@RequestMapping("/getPage")
	public R getPage(ThirdLandingPageVo req,Page<ThirdLandingPage> page) {
		//获取到当前登录用户
		Integer id = SecurityUtils.getUser().getId();
		//通过登录用户去查询多个广告主id
		List<String> allList = advService.getOwnerAdv(id, PlatformTypeEnum.TT.getValue());
		if(allList == null || allList.size() == 0) {
			return R.ok(page);
		}
		//设置where条件
		QueryWrapper<ThirdLandingPage> queryWrapper = new QueryWrapper<>();
		//查询所有
		queryWrapper.in("advertiser_id", allList);
		//根据广告主id查询
		String[] advArr = req.getAdvertiserIds();
		if (advArr != null && advArr.length > 0) {
			List<String> selectList = Arrays.asList(advArr);
			if (!allList.containsAll(selectList)) {
				return R.failed("广告账户不可用");
			}
			queryWrapper.in("advertiser_id", selectList);
		}
		//根据落地页名称模糊查询
		if (!StringUtils.isBlank(req.getPageName())){
			queryWrapper.like("page_name", req.getPageName());
		}
		//根据落地页id精确查询
		if (!StringUtils.isBlank(req.getPageId())){
			queryWrapper.eq("page_id",req.getPageId());
		}
		//根据创建时间降序
		queryWrapper.orderByDesc("create_time");
		IPage<ThirdLandingPage> oIPage = tlpMapper.selectPage(page, queryWrapper);
		return R.ok(oIPage, "操作成功");
	}

	//获取预览地址
	@RequestMapping("/preview")
	public R previewById(Integer id){
		ThirdLandingPage req = tlpMapper.selectById(id);
		String purl = getUrl(req);
		return R.ok(purl,"操作成功");
	}
	//调用第三方投放平台接口，获取预览地址
	public String getUrl(ThirdLandingPage thirdLandingPage) {
		String thirdSitePreviewUrl = "https://ad.oceanengine.com/open_api/2/tools/third_site/preview/";
		Map<String, Object> data = new HashMap<String, Object>();
		String advertiserId = thirdLandingPage.getAdvertiserId();
		String pageId = thirdLandingPage.getPageId();
		data.put("advertiser_id", advertiserId);
		data.put("site_id", pageId);
		String accessToken = ttAccesstokenService.fetchAccesstoken(advertiserId);
		//调第三方平台（头条）接口
		String resultStr = OEHttpUtils.doGet(thirdSitePreviewUrl, data, accessToken);
		ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
		String purl = null;
		if (resBean != null && "0".equals(resBean.getCode())) {
			JSONObject jsonObj = resBean.getData();
			purl = jsonObj.getString("url");
		}
		if (StringUtils.isBlank(purl)){
			purl = thirdLandingPage.getUrl();
			return purl;
		}
		return purl;
	}

	//修改落地页名称
	@RequestMapping("/modify")
	public R modify(ThirdLandingPage req){
		return tlpService.updateSelective(req);
	}

	//添加落地页
	@RequestMapping("/create")
	public R create(ThirdLandingPage req){
		return tlpService.create(req);
	}

	//根据id查询:修改时回显
	@RequestMapping("/findById")
	public R getById(Integer id){
		ThirdLandingPage thirdLandingPage = tlpMapper.selectById(id);
		return R.ok(thirdLandingPage,"操作成功");
	}

	@RequestMapping("/getSelectPage")
	public R getSelectPage(ThirdLandingPageVo req,Page<ThirdLandingPage> page) {
		//获取到当前登录用户
		Integer id = SecurityUtils.getUser().getId();
		//通过登录用户去查询多个广告主id
		List<String> allList = advService.getOwnerAdv(id, PlatformTypeEnum.TT.getValue());
		if (allList == null || allList.isEmpty()) {
			return R.ok(page);
		}
		//设置where条件
		QueryWrapper<ThirdLandingPage> queryWrapper = new QueryWrapper<>();
		//根据广告主id查询
		String adv = req.getAdvertiserId();
		if (StringUtils.isBlank(adv)) {
			return R.failed("未传入广告主id");
		}
		if (!allList.contains(adv)) {
			return R.failed("广告账户不可用");
		}
		queryWrapper.eq("advertiser_id", adv);
		//根据落地页名称模糊查询
		if (!StringUtils.isBlank(req.getPageName())) {
			queryWrapper.like("page_name", req.getPageName());
		}
		//根据落地页id精确查询
		if (!StringUtils.isBlank(req.getPageId())){
			queryWrapper.eq("page_id",req.getPageId());
		}
		//根据创建时间降序
		queryWrapper.orderByDesc("create_time");
		IPage<ThirdLandingPage> oIPage = tlpMapper.selectPage(page, queryWrapper);
		return R.ok(oIPage, "操作成功");
	}
}


